// app.ts

import { httpRequest } from "./utils/httpRequest"

export interface IMyApp extends IAppOption {
  globalData: {
    userInfo?: WechatMiniprogram.UserInfo,
    appletid: string, /* 用来支持一个后台多个前端小程序 */
    apisite: string,
    openid?: string,  // openid: "o_w694sCgBCibBH7U9Y5YwGZ9gUg", session_key: "qY24ez4sso4lb963GPntnQ=="
    session_key?: string
  }
  userInfoReadyCallback?: WechatMiniprogram.GetUserInfoSuccessCallback,

  http: httpRequest,
}

App<IMyApp>({
  globalData: {
    apisite:"http://localhost:8020",
    appletid:"10001"
  },
  http: new httpRequest(),
  onLaunch() {
    let self = this;
    self.http._header.applet_id = self.globalData.appletid;
    
    // 展示本地存储能力
    // const logs = wx.getStorageSync('logs') || []
    // logs.unshift(Date.now())
    // wx.setStorageSync('logs', logs)

    // 登录
    wx.login({
      success: res => {

        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        let code = res.code; 
        let url = self.globalData.apisite + '/appletapi/wxlogin';
        let appletid = self.globalData.appletid;
        self.http.postRequest(url, "code=" + code + "&appletid=" + appletid).then(json => {
          if (json.flag) {
            self.globalData.openid = json.data.openid;
            self.globalData.session_key = json.data.session_key;
            self.http._header.applet_token = self.globalData.openid;
          }
          else {
            wx.showToast({
              title: json.msg,
              icon: 'none',
              duration: 2000
            });
          }
        });
      },
    })

  },
  onError(errorString: string){
      console.error(errorString);
  }
})